package controller;


import entity.Cart;
import service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
@RequestMapping("cart")
public class CartController {
    /**
     * 服务对象
     */
    @Autowired
    private CartService cartService;

    /**
     * 分页查询
     *
     * @param cart 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Cart>> queryByPage(Cart cart, PageRequest pageRequest) {
        return ResponseEntity.ok(this.cartService.queryByPage(cart, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("query/{id}")
    public ResponseEntity<Cart> queryById(@PathVariable("id") Integer id) {
        System.out.println(this.cartService.queryById(id));
        return ResponseEntity.ok(this.cartService.queryById(id));
    }

    @PostMapping("addProductIntoCart")
    public long add(@RequestBody @Validated Cart cart) {
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
        cart.setUpdateTime(timestamp);
        if(this.cartService.queryById(cart.getProId())!=null){
            this.cartService.update(cart);
        }else{
            this.cartService.insert(cart);
        }
        return this.cartService.countTotalRecords();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.cartService.deleteById(id));
    }

    @GetMapping("countTotalRecords")
    public ResponseEntity<Long> countTotalRecords(){
        return ResponseEntity.ok(this.cartService.countTotalRecords());
    }
}

